
#include <cmath>

#include "procycle.h"
#include "timeaxis.h"
#include "ganttscene.h"


TimeAxis::TimeAxis(ProCycle *app) :
    PCChild(app),
    m_length(1),
    m_scale(1),
    m_lastScale(0),
    m_lastWidth(0)
{}

void TimeAxis::setLength(const int& length) {
    m_length = length;
    m_scale = app()->ganttScene()->width() / m_length;
}



void TimeAxis::setScale(const double& scale) {
    m_scale = scale;
    m_length = app()->ganttScene()->width() / m_scale;
}



const float INTER_COEFS [] = { 2, 2.5, 2 };   // 1, 2, 5, 10, 20, 50 ...

const float MIN_INTER_GRADS = 40;

float round(float num)
{
  return std::floor(num + 0.5f);
}


void TimeAxis::updateGrads() {

    int w = app()->ganttScene()->width();
    if (w == m_lastWidth && m_scale == m_lastScale) {
        return;
    }

    m_lastWidth = w;
    m_lastScale = m_scale;

    m_grads.clear();
    float u2p = unit2px();
    float interG = 1.f;
    int i=0;
    while (interG*u2p < MIN_INTER_GRADS) {
        interG *= INTER_COEFS[i];
        if (++i == 3) {
            i = 0;
        }
    }
    int gradCount = px2unit(w)/interG + 1;

    Grad g;

    for (i=0; i<gradCount; i++) {
        g.time = i*interG;
        g.pos = round(u2p * g.time);
        m_grads.push_back(g);
    }
}
